package com.bbx.demo.nio;

import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

@Slf4j
public class ChannelTest {

    public static void main(String[] args) throws Exception {
        //把文件内容读入 buffer 中
        FileInputStream fileInputStream = new FileInputStream("./src/main/resources/fileInput.txt");
        FileChannel channel = fileInputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(512);
        channel.read(byteBuffer);
        //buffer 反转
        byteBuffer.flip();
        while (byteBuffer.hasRemaining()) {
            byte b = byteBuffer.get();
            log.info("fileInput中内容[{}]", (char) b);
        }

        //将内容写出到文件
        FileOutputStream fileOutputStream = new FileOutputStream("./src/main/resources/fileOutput.txt");
        FileChannel channel1 = fileOutputStream.getChannel();
        ByteBuffer allocate = ByteBuffer.allocate(512);
        //将数据写入 buffer中
        allocate.put("Hello Output".getBytes());
        //因为要将数据写出 ，因此必须要进行反转
        allocate.flip();
        //从Buffer 中读取数据写出，
        channel1.write(allocate);
        fileOutputStream.close();
        fileInputStream.close();
    }
}
